package com.szl.yeb.utils;


import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: yeb
 * @description: 将List转换成以某一属性为key的Map
 * @author: szl
 * @create: 2022-09-03 00:17
 **/
public class ListToMapUtil {

    public static <E> Map<Object, E> list2Map(List<E> list, String fieldName) {
        Map<Object, E> map = new HashMap<>();
        list.forEach(item -> {
            try {
                Field field = item.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Object fieldValue = field.get(item);
                map.put(fieldValue, item);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return map;
    }
}
